package com.xs.client.handler;

import java.io.IOException;
import java.util.Date;
import java.util.Scanner;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.xs.entity.Message;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ClientHandler extends ChannelInboundHandlerAdapter {

	private static final Logger logger = Logger.getLogger(ClientHandler.class);

	
	private String userName;
	
	/**
	 * 
	 */
	public ClientHandler() {
		// TODO Auto-generated constructor stub
	}
	
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		logger.info("客户端收到消息内容为：" + msg);
		String uName = msg.toString().substring(0,3);
		userName = uName;
		//ctx.writeAndFlush("客户说：当前时间是" + new Date()+"\r\n");
		
		sendMsg(ctx);
		

		
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		logger.error(cause);
		if (ctx != null) {
			ctx.close();
		}
	}

	
	
	public void sendMsg(ChannelHandlerContext ctx) throws IOException {
		Scanner scan = new Scanner(System.in);
	    String read = scan.nextLine();
	    Message recieveMsge =  new Message();
	    recieveMsge.setContent(read);
	    recieveMsge.setUserName(userName);
	    if(userName.equals("001")){
	    	recieveMsge.setTargetName("002");
	    }else{
	    	recieveMsge.setTargetName("001");
	    }
	    ctx.writeAndFlush(JSON.toJSONString(recieveMsge) + "\r\n");
		
	}
	
}
